package dsync

import (
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"log"
	"regexp"
	"time"
)

var Cfg Config
var App AppCfg

type Config struct {
	//Log    bool
	//Domain string
	//Port   string
	App  AppCfg
	Sync Sync
	Rkws []Rkw
}

type AppCfg struct {
	Log    bool
	Domain string
	Port   string
}

type Rkw struct {
	RR    string
	Type  string
	Sites []string
}

type Sync struct {
	Delay time.Duration
	Ddns  bool
}

func GetConfig() Config {
	log.Println("读取并解析配置文件")
	file, err := ioutil.ReadFile("config.yaml")
	if err != nil {
		log.Printf("yaml file.Get err #%v ", err)
		log.Panic("yaml file.Get err")
	}
	config := Config{}
	err = yaml.Unmarshal(file, &config)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}
	log.Printf("配置文件读取完成: %+v\n", config)
	App = config.App
	check(&config)
	return config
}

func check(cfg *Config) {
	log.Println("开始效验配置文件")
	if isNil(cfg.App.Domain) {
		log.Panic("domain 域名不能为空")
	}
	if cfg.Sync.Delay <= 5 {
		cfg.Sync.Delay = 10
	}
	if isNil(cfg.App.Port) {
		cfg.App.Port = "10000"
	}
	for _, v := range cfg.Rkws {
		if isNil(v.RR) {
			log.Panic("sld 解析二级域名不能为空")
		}
		if isNil(v.Type) {
			v.Type = "A"
		}
	}
}

var reg = regexp.MustCompile("\\s+")

func isNil(val string) bool {
	if val == "" {
		return true
	}
	val = reg.ReplaceAllString(val, "")
	if val == "" {
		return true
	}
	return false
}
